import React, { useState, useEffect, useRef } from 'react';
import { Layout } from 'antd';
import HistoryList from './components/HistoryList/HistoryList';
import ChatContent from './components/ChatContent/ChatContent';
import DataTable from './components/DataTable/DataTable';
import './KimiChat.scss';

const { Sider, Content } = Layout;

export interface ChatMessage {
    id: string;
    content: string;
    timestamp: Date;
    type: 'user' | 'assistant';
    status?: 'pending' | 'accepted' | 'rejected';
}

export interface ChatSession {
    id: string;
    title: string;
    messages: ChatMessage[];
    tableData: TableData[];
    createdAt: Date;
    updatedAt: Date;
}

export interface TableData {
    id: string;
    name: string;
    value: number;
    category: string;
    status: string;
    date: string;
}

const KimiChat: React.FC = () => {
    const [sessions, setSessions] = useState<ChatSession[]>([]);
    const [currentSessionId, setCurrentSessionId] = useState<string | null>(null);
    const [isWaitingForResponse, setIsWaitingForResponse] = useState(false);
    const [pendingResponses, setPendingResponses] = useState<ChatMessage[]>([]);
    const eventSource = useRef<EventSource | null>(null);

    const currentSession = sessions.find(session => session.id === currentSessionId);

    const handleCreateSession = () => {
        const newSession: ChatSession = {
            id: Date.now().toString(),
            title: `新对话 ${sessions.length + 1}`,
            messages: [],
            tableData: [],
            createdAt: new Date(),
            updatedAt: new Date()
        };
        setSessions(prev => [newSession, ...prev]);
        setCurrentSessionId(newSession.id);
    };

    const handleDeleteSession = (sessionId: string) => {
        setSessions(prev => prev.filter(session => session.id !== sessionId));
        if (currentSessionId === sessionId) {
            setCurrentSessionId(null);
        }
    };

    const handleSelectSession = (sessionId: string) => {
        setCurrentSessionId(sessionId);
    };

    // 初始化SSE连接
    useEffect(() => {
        eventSource.current = new EventSource('http://localhost:8080/sse');
        
        eventSource.current.onopen = () => {
            console.log('SSE连接已建立');
        };
        
        eventSource.current.onmessage = (event) => {
            try {
                const data = JSON.parse(event.data);
                console.log('收到SSE消息:', data);
                
                if (data.type === 'response') {
                    const assistantMessage: ChatMessage = {
                        id: data.messageId?.toString() || Date.now().toString(),
                        content: data.content,
                        timestamp: new Date(),
                        type: 'assistant',
                        status: 'pending'
                    };
                    
                    setPendingResponses(prev => [...prev, assistantMessage]);
                    
                    // 如果是最后一条消息，设置完成状态
                    if (data.isLast) {
                        setTimeout(() => {
                            setIsWaitingForResponse(false);
                        }, 500);
                    }
                } else if (data.type === 'complete') {
                    setIsWaitingForResponse(false);
                } else if (data.type === 'data') {
                    // 更新对应会话的表格数据
                    if (data.sessionId) {
                        setSessions(prevSessions => prevSessions.map(session => {
                            if (session.id === data.sessionId) {
                                return {
                                    ...session,
                                    tableData: data.content,
                                    updatedAt: new Date()
                                };
                            }
                            return session;
                        }));
                    }
                }
            } catch (error) {
                console.error('解析SSE消息失败:', error);
            }
        };
        
        eventSource.current.onerror = (error) => {
            console.error('SSE错误:', error);
        };
        
        return () => {
            if (eventSource.current) {
                eventSource.current.close();
            }
        };
    }, []);
    
    // 请求表格数据的函数
    const requestTableData = async () => {
        if (currentSessionId) {
            try {
                void fetch('http://localhost:8080/send-message', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        type: 'request_data',
                        content: '请求表格数据',
                        sessionId: currentSessionId
                    })
                });
                console.log('已发送数据请求，会话ID:', currentSessionId);
            } catch (error) {
                console.error('发送数据请求失败:', error);
            }
        }
    };

    const handleSendMessage = async (content: string) => {
        if (!currentSessionId || isWaitingForResponse) return;
        
        setIsWaitingForResponse(true);
        setPendingResponses([]);
        
        const userMessage: ChatMessage = {
            id: Date.now().toString(),
            content,
            timestamp: new Date(),
            type: 'user'
        };
        
        // 添加用户消息到会话
        setSessions(prev => prev.map(session => {
            if (session.id === currentSessionId) {
                return {
                    ...session,
                    messages: [...session.messages, userMessage],
                    updatedAt: new Date()
                };
            }
            return session;
        }));
        
        // 通过HTTP POST发送消息
        try {
            void fetch('http://localhost:8080/send-message', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    type: 'message',
                    content: content
                })
            });
            console.log('已发送消息:', content);
        } catch (error) {
            console.error('发送消息失败:', error);
            setIsWaitingForResponse(false);
        }
    };
    
    const handleAcceptResponse = (messageId: string) => {
        setPendingResponses(prev => {
            const messageToAccept = prev.find(msg => msg.id === messageId);
            if (messageToAccept) {
                const acceptedMessage = { ...messageToAccept, status: 'accepted' as const };
                
                // 添加到当前会话
                setSessions(prevSessions => prevSessions.map(session => {
                    if (session.id === currentSessionId) {
                        return {
                            ...session,
                            messages: [...session.messages, acceptedMessage],
                            updatedAt: new Date()
                        };
                    }
                    return session;
                }));
                
                // 从待处理列表中移除
                const updatedPending = prev.filter(msg => msg.id !== messageId);
                
                // 如果所有消息都已处理，请求数据
                if (updatedPending.length === 0) {
                    requestTableData();
                }
                
                return updatedPending;
            }
            return prev;
        });
    };
    
    const handleRejectResponse = (messageId: string) => {
        setPendingResponses(prev => {
            const updatedPending = prev.filter(msg => msg.id !== messageId);
            
            // 如果所有消息都已处理，请求数据
            if (updatedPending.length === 0) {
                requestTableData();
            }
            
            return updatedPending;
        });
    };
    
    const handleAcceptAllResponses = () => {
        const acceptedMessages = pendingResponses.map(msg => ({ ...msg, status: 'accepted' as const }));
        
        // 添加所有消息到当前会话
        setSessions(prevSessions => prevSessions.map(session => {
            if (session.id === currentSessionId) {
                return {
                    ...session,
                    messages: [...session.messages, ...acceptedMessages],
                    updatedAt: new Date()
                };
            }
            return session;
        }));
        
        // 清空待处理列表并请求数据
        setPendingResponses([]);
        requestTableData();
    };
    
    const handleRejectAllResponses = () => {
        setPendingResponses([]);
        requestTableData();
    };

    return (
        <Layout className="kimi-chat">
            <Sider width={280} theme="light" className="kimi-chat__sidebar">
                <HistoryList
                    sessions={sessions}
                    currentSessionId={currentSessionId}
                    onCreateSession={handleCreateSession}
                    onDeleteSession={handleDeleteSession}
                    onSelectSession={handleSelectSession}
                />
            </Sider>
            <Content className="kimi-chat__main">
                <ChatContent
                    session={currentSession}
                    onSendMessage={handleSendMessage}
                    isWaitingForResponse={isWaitingForResponse}
                    pendingResponses={pendingResponses}
                    onAcceptResponse={handleAcceptResponse}
                    onRejectResponse={handleRejectResponse}
                    onAcceptAllResponses={handleAcceptAllResponses}
                    onRejectAllResponses={handleRejectAllResponses}
                />
            </Content>
            <Sider width={400} theme="light" className="kimi-chat__data">
                <DataTable 
                    data={currentSession?.tableData || []} 
                    sessionTitle={currentSession?.title}
                />
            </Sider>
        </Layout>
    );
};

export default KimiChat;